import 'package:flutter/services.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_plateconsumption_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_plateconsumption.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/pages/odoo/product_plateconsumption/product_plateconsumption_edit.dart';
import 'package:flutter_admin/pages/odoo/product_plateconsumption/product_plateconsumption_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';

class ProductPlateconsumptionList extends StatefulWidget {
  ProductPlateconsumptionList({Key? key}) : super(key: key);

  @override
  _ProductPlateconsumptionListState createState() =>
      _ProductPlateconsumptionListState();
}

class _ProductPlateconsumptionListState
    extends State<ProductPlateconsumptionList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ProductPlateconsumption productPlateconsumption = ProductPlateconsumption();
  List<ProductPlateconsumption> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');
  UdtTbWorkreportrecord udtTbWorkreportrecordScan = UdtTbWorkreportrecord();
  //报工人员
  late List<SelectOptionVO> reportworkerList = [];
  late var _subscription;
  late var _subscription1;
  ValueNotifier<bool> isLoading = ValueNotifier<bool>(true);

  @override
  void initState() {
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "productPlateconsumption")
        .listen(_onEnvent);
    _subscription1 = EventBus.getSubscriber()
        .where((event) => event["key"] == "productPlateconsumptionDelete")
        .listen(_scanDelete);
    super.initState();
    productPlateconsumption.filledDateStart = Utils.getDate()+" 00:00:00";
    productPlateconsumption.filledDateEnd = Utils.getDate()+" 23:59:59";
    // _subscription = eventChannel.receiveBroadcastStream().listen(_onEnvent,onError: _onError);
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    _subscription1.cancel();
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) {
    try {
      _getStation(obj["scan"].toString());
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  // void _onError(Object obj) {}

  _getStation(barcode) async {
    // todo 设备工位
    ResponseBodyApi res = await DynamicDataApi.getModels(
        model: "base.productionstation", key: 'stationcode', val: barcode);
    if (res.success!) {
      if (res.data.length == 0) {
        CryUtils.message("该设备工位编码已失效");
        return;
      } else if (res.data.length > 1) {
        CryUtils.message("设备工位编码重复");
        return;
      } else {
        // 查找对应班组
        ResponseBodyApi teamRes = await DynamicDataApi.getModels(
            model: "base.team", key: 'id', val: res.data[0]["team_id"][0]);
        if (!teamRes.success!) {
          return;
        }
        if (teamRes.data.length == 0) {
          CryUtils.message("数据错误");
          return;
        }
        // formKey.currentState!.save();
        udtTbWorkreportrecordScan.stationId = res.data[0]["id"].toString();
        udtTbWorkreportrecordScan.stationCode = barcode;
        udtTbWorkreportrecordScan.stationName =
            res.data[0]["stationname"].toString();
        udtTbWorkreportrecordScan.factoryId =
            res.data[0]["factory_id"][0].toString();
        udtTbWorkreportrecordScan.factoryName =
            res.data[0]["factory_id"][1].toString();
        udtTbWorkreportrecordScan.workshopId =
            res.data[0]["workshop_id"][0].toString();
        udtTbWorkreportrecordScan.workshopName =
            res.data[0]["workshop_id"][1].toString();
        udtTbWorkreportrecordScan.teamId = teamRes.data[0]["id"].toString();
        udtTbWorkreportrecordScan.teamCode =
            teamRes.data[0]["teamcode"].toString();
        udtTbWorkreportrecordScan.teamName =
            teamRes.data[0]["teamname"].toString();
        // todo 获取该班组下的所有人员
        ResponseBodyApi resUser = await DynamicDataApi.getModels(
            model: "base.teamuser", key: "team_id", val: teamRes.data[0]["id"]);
        if (resUser.success!) {
          if (resUser.data.length == 0) {
            CryUtils.message("该班组下没有人员,请绑定人员");
            return;
          }
          reportworkerList = [];
          for (int i = 0; i < resUser.data.length; i++) {
            reportworkerList.add(SelectOptionVO(
                value: resUser.data[i]["staff_id"][0].toString(),
                label: resUser.data[i]["staff_id"][1].toString()));
          }
          CryUtils.message("绑定${udtTbWorkreportrecordScan.stationName}设备工位成功");
          StoreUtil.write(Constant.KEY_PRODUCTIONSTATION,
              udtTbWorkreportrecordScan.toMap());
          StoreUtil.write(Constant.KEY_REPORTWORKERLIST, reportworkerList);
          // todo 获取工位下的工序
          ResponseBodyApi stationPath = await DynamicDataApi.getModels(
              model: "base.teampath",
              key: "team_id",
              val: teamRes.data[0]["id"]);
          if (stationPath.success! && stationPath.data.length != 0) {
            var pathList = [];
            for (int i = 0; i < stationPath.data.length; i++) {
              pathList.add(SelectOptionVO(
                  value: stationPath.data[i]["process_id"][0].toString(),
                  label: stationPath.data[i]["process_id"][1].toString()));
            }
            StoreUtil.write(Constant.KEY_PATHLIST, pathList);
          }
          _query();
          setState(() {});
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          DateTimeSelect(
            context,
            width: 230,
            label: '填报开始日期',
            value: productPlateconsumption.filledDateStart,
            lastDate: productPlateconsumption.filledDateEnd != '' &&
                    productPlateconsumption.filledDateEnd != null
                ? format.parse(productPlateconsumption.filledDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productPlateconsumption.filledDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              productPlateconsumption.filledDateStart = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '填报结束时间',
            value: productPlateconsumption.filledDateEnd,
            firstDate: productPlateconsumption.filledDateStart != '' &&
                    productPlateconsumption.filledDateStart != null
                ? format.parse(productPlateconsumption.filledDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productPlateconsumption.filledDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              productPlateconsumption.filledDateEnd = v;
            },
          ),
          CryInput(
            width: 160,
            label: '板材名称',
            value: productPlateconsumption.productName,
            onSaved: (v) {
              productPlateconsumption.productName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '填报人',
            value: productPlateconsumption.filledName,
            onSaved: (v) {
              productPlateconsumption.filledName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              Tooltip(
                message: '添加',
                child: IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    _edit(null);
                  },
                ),
              ),
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('板材名称')),
        DataColumn(label: Text('厚度(mm)')),
        DataColumn(label: Text('长度(mm)')),
        DataColumn(label: Text('宽度(mm)')),
        DataColumn(label: Text('重量(KG)')),
        DataColumn(label: Text('消耗张数(张)')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('设备工位')),
        DataColumn(label: Text('填报人')),
        DataColumn(label: Text('填报时间')),
        DataColumn(label: Text('修改人')),
        DataColumn(label: Text('修改时间')),
      ],
      getCells: (m) {
        ProductPlateconsumption productPlateconsumption =
            ProductPlateconsumption.fromMap(m);
        return [
          DataCell(Text(productPlateconsumption.productName ?? '--')),
          DataCell(Text(productPlateconsumption.thicknessName ?? '--')),
          DataCell(Text(productPlateconsumption.length.toString())),
          DataCell(Text(productPlateconsumption.width.toString())),
          DataCell(Text(productPlateconsumption.weight.toString())),
          DataCell(Text(productPlateconsumption.consumednumber.toString())),
          DataCell(Text(productPlateconsumption.remark ?? '--')),
          DataCell(Text(productPlateconsumption.stationName ?? '--')),
          DataCell(Text(productPlateconsumption.filledName ?? '--')),
          DataCell(Text(productPlateconsumption.filledDate ?? '--')),
          DataCell(Text(productPlateconsumption.writeName ?? '--')),
          DataCell(Text(productPlateconsumption.writeDate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(
            context,
            selectedList.length != 0
                ? () => _delete(selectedList)
                : null),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _generateExcel() async {
    List<ProductPlateconsumption> selectedList = await findAll();
    List<Map> map = [
      {
        'name': 'productName',
        'label': '板材名称',
        'columnWidth': 14.0,
      },
      {
        'name': 'thicknessName',
        'label': '厚度(mm)',
        'columnWidth': 12.0,
      },
      {
        'name': 'length',
        'label': '长度(mm)',
        'columnWidth': 12.0,
      },
      {
        'name': 'width',
        'label': '宽度(mm)',
        'columnWidth': 12.0,
      },
      {
        'name': 'weight',
        'label': '重量(KG)',
        'columnWidth': 12.0,
      },
      {
        'name': 'consumednumber',
        'label': '消耗张数(张)',
        'columnWidth': 16.0,
      },
      {
        'name': 'remark',
        'label': '备注',
        'columnWidth': 10.0,
      },
      {
        'name': 'stationName',
        'label': '设备工位',
        'columnWidth': 13.0,
      },
      {
        'name': 'filledName',
        'label': '填报人',
        'columnWidth': 10.0,
      },
      {
        'name': 'filledDate',
        'label': '填报时间',
        'columnWidth': 20.0,
      },
      {
        'name': 'writeName',
        'label': '修改人',
        'columnWidth': 10.0,
      },
      {
        'name': 'writeDate',
        'label': '修改时间',
        'columnWidth': 20.0,
      }
    ];
    Utils.generateExcel(fileName: "板材消耗", configure: map, data: selectedList);
  }

  _edit(ProductPlateconsumption? productPlateconsumption) async {
    // 手机端需要先绑定工位再进行查看
    if (!isDisplayDesktop(Cry.context)) {
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST)) {
        CryUtils.message("请绑定钣金-数冲工位");
        return;
      } else if (StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)["teamCode"] !=
          "BJSC") {
        CryUtils.message(
            "${StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)['stationName']}没有查看权限");
        return;
      }
    }
    StoreUtil.write("key", "plateconsumptionEdit");
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductPlateconsumptionEdit(
          productPlateconsumption: productPlateconsumption,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(productPlateconsumption == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    productPlateconsumption = ProductPlateconsumption();
    productPlateconsumption.filledDateStart = Utils.getDate()+" 00:00:00";
    productPlateconsumption.filledDateEnd = Utils.getDate()+" 23:59:59";
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  void _scanDelete(dynamic obj) async{
    try {
      ResponseBodyApi res = await DynamicDataApi.getModels(
          model: "res.users", key: 'login', val: obj["scan"]);
      if (res.success!) {
        if (res.data.length == 0) {
          CryUtils.message("该人员不存在");
          return;
        } else if (res.data.length > 1) {
          CryUtils.message("编号重复");
          return;
        } else {
          if(selectedList[0].filledUid != res.data[0]["id"].toString()){
            CryUtils.message("您没有权限");
            setState(() {});
            return;
          }
          isLoading.value = false;
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  void deleteConfirm(BuildContext context, String content, onConfirm) {
    StoreUtil.write("key", "productPlateconsumptionDelete");
    isLoading.value = true;
    showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return ValueListenableBuilder<bool>(
          valueListenable: isLoading,
          builder: (context, value, child) {
            return AlertDialog(
              title: Text(S.of(context).information),
              content: value?Text("请扫描人员",style: TextStyle(
                  fontSize: 36, color: Colors.red
              ),):Text(content),
              actions: <Widget>[
                TextButton(
                  child: Text(S.of(context).cancel),
                  onPressed: () {
                    Navigator.of(context).pop();
                    StoreUtil.write("key", "productPlateconsumption");
                  },
                ),
                TextButton(
                  child: Text(S.of(context).confirm),
                  onPressed: value?null:() {
                    Navigator.of(context).pop();
                    onConfirm(context);
                    StoreUtil.write("key", "productPlateconsumption");
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  _delete(List<ProductPlateconsumption> selectedList) async {
    if(isDisplayDesktop(context)){
      cryConfirm(context, S.of(context).confirmDelete, (context) async {
        List ids = selectedList.map((v) {
          return int.parse(v.id!);
        }).toList();
        var result = await ProductPlateconsumptionOdooApi.removeByIds(ids);
        if (result.success!) {
          CryUtils.message("删除成功");
          _query();
        }
      });
    }else{
      deleteConfirm(context, S.of(context).confirmDelete, (context) async {
        List ids = selectedList.map((v) {
          return int.parse(v.id!);
        }).toList();
        var result = await ProductPlateconsumptionOdooApi.removeByIds(ids);
        if (result.success!) {
          CryUtils.message("删除成功");
          _query();
        }
      });
    }
  }

  _loadData() async {
    // 手机端需要先绑定工位再进行查看
    if (!isDisplayDesktop(Cry.context)) {
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST)) {
        CryUtils.message("请绑定钣金-数冲");
        return;
      } else if (StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)["teamCode"] !=
          "BJSC") {
        CryUtils.message(
            "${StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)['stationName']}没有查看权限");
        return;
      }
    }
    ResponseBodyApi responseBodyApi = await ProductPlateconsumptionOdooApi.page(
        data: {
          "page": page,
          "domainList": productPlateconsumption.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState?.loadData(page);
      _getSelectList();
    }
  }

  Future<List<ProductPlateconsumption>> findAll() async {
    formKey.currentState?.save();
    List<ProductPlateconsumption> resultList = [];
    ResponseBodyApi responseBodyApi =
        await ProductPlateconsumptionOdooApi.findAll(
            data: {"domainList": productPlateconsumption.toDomainList()});
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<ProductPlateconsumption>(
                  (e) => ProductPlateconsumption.fromMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductPlateconsumptionDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productPlateconsumption = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductPlateconsumption>(
                (e) => ProductPlateconsumption.fromMap(e))
            .toList() ??
        [];
    // setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          // _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        }else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        // PopupMenuItem<OperationType>(
        //   value: OperationType.add,
        //   child: ListTile(
        //     leading: const Icon(Icons.add),
        //     title: Text('添加'),
        //   ),
        // ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length == 1,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
